<?php
namespace app\process;

use Workerman\Connection\TcpConnection;
use Workerman\Worker;

class WebSocketProcess
{
    public function __construct()
    {
        // 创建一个 WebSocket 服务实例
        $ws_worker = new Worker('websocket://0.0.0.0:8788');

        // 启动 4 个进程对外提供服务
        $ws_worker->count = 4;

        // 存储所有连接的客户端
        $clients = [];

        // 当有新的客户端连接时
        $ws_worker->onConnect = function (TcpConnection $connection) use (&$clients) {
            $clients[$connection->id] = $connection;
        };

        // 当接收到客户端消息时
        $ws_worker->onMessage = function (TcpConnection $connection, $data) use (&$clients) {
            // 遍历所有连接的客户端
            foreach ($clients as $client) {
                if ($client != $connection) {
                    // 向除发送者之外的其他客户端广播消息
                    $client->send($data);
                }
            }
        };

        // 当客户端断开连接时
        $ws_worker->onClose = function (TcpConnection $connection) use (&$clients) {
            unset($clients[$connection->id]);
        };

        // 运行 worker
        Worker::runAll();
    }
}